package com.zly.framework.rbac.model.entity;


import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.media.SchemaProperty;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.io.Serial;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * @author 钟刘扬
 */
@Slf4j
@Schema(name = "用户信息")
public class SecurityUserDetails extends User implements UserDetails {

    @Serial
    private static final long serialVersionUID = 1L;

    private List<Permission> permissionList;

    private List<Role> roleList;

    @Override
    @SchemaProperty(name = "查询用户的角色和菜单权限")
    public Collection<? extends GrantedAuthority> getAuthorities() {
        ArrayList<GrantedAuthority> grantedAuthorities = new ArrayList<>();
//        防止空指针异常
        if (!permissionList.isEmpty()) {
            for (Permission permission : permissionList) {
                grantedAuthorities.add(new SimpleGrantedAuthority(permission.getName()));
            }
        }
        if (!roleList.isEmpty()) {
            for (Role role : roleList) {
                grantedAuthorities.add(new SimpleGrantedAuthority(role.getName()));
            }
        }
        return grantedAuthorities;
    }

    @Override
    public boolean isEnabled() {
        return true;
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    /**
     * 自定义类构造器
     *
     * @param user 系统账户
     */
    public SecurityUserDetails(User user) {
        if (user != null) {
            this.setUsername(user.getUsername());
            this.setPassword(user.getPassword());
            this.permissionList = user.getPermissions();
            this.roleList = user.getRoles();
        }
    }
}